package com.example.mybatisstudy.service;

import com.example.mybatisstudy.mapper.UserInfoMapper;
import com.example.mybatisstudy.model.UserInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.Transaction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Context {
    private static final String resource = "mybatis-config.xml";
    private static SqlSession session;

    @BeforeEach
    public void init() throws IOException {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 读取配置文件为输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 通过输入流构建 会话工厂
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 通过会话工厂创建一个会话
        session = sqlSessionFactory.openSession();
    }

    @Test
    void test() {
        List<Object> objectList = new ArrayList<>();
        ResultHandler handler = new ResultHandler() {
            // ResultContext 用来控制结果的行数
            @Override
            public void handleResult(ResultContext resultContext) {
                if(resultContext.getResultCount()==1){
                    resultContext.stop();
                }
                objectList.add(resultContext.getResultObject());
            }
        };
        session.select("com.example.mybatisstudy.mapper.UserInfoMapper.listUser",handler);
        System.out.println(objectList.size());
    }

    @Test
    @DisplayName("测试简单的映射")
    void name1() {
        UserInfoMapper mapper = session.getMapper(UserInfoMapper.class);
        mapper.selectUser("1");
    }

    @Test
    @DisplayName("测试映射结果集")
    void name() {
        UserInfoMapper mapper = session.getMapper(UserInfoMapper.class);
        UserInfo userInfo = mapper.selectUser03("1");
        System.out.println(userInfo);
    }
}
